package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

type Download struct {
	RequestUri string
	MaxNum     int
}

func (d *Download) FileName(uri string) string {
	return string([]byte(uri)[strings.LastIndex(uri, "/")+1:])
}

func (d *Download) GetFile(num int) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("===> Get file error:", err, ",Num:", num)
		}
	}()
	uri := fmt.Sprintf(d.RequestUri, num)
	response, err := http.Get(uri)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	file, err := os.Create(fmt.Sprintf("./images/%s", d.FileName(uri)))
	if err != nil {
		panic(err)
	}
	defer file.Close()
	io.Copy(file, response.Body)
	// fmt.Println("===> Get file ", num, " success.")
}

func (d *Download) GetMultipleFile() {
	for i := 1; i < d.MaxNum; i++ {
		go d.GetFile(i)
	}
}

func main() {
	ch := make(chan bool, 1)
	dl := &Download{
		RequestUri: "https://coding.net/static/project_icon/scenery-%v.png",
		MaxNum:     25,
	}
	dl.GetMultipleFile()
	<-ch
}
